import React, {Component} from 'react';
import {FormGroup, Input, Toast} from '@welab/xlib-react-components';
import Agreement from '../component/Agreement';
import Validate from '../helper/validator';
import Config from '../helper/config';
import FullScreen from "../component/FullScreen";

class SubmitApply extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      verCodeError: 'none',
      verifyCode: '',
      getVerBtnText: '获取验证码',
      getVerAllow: true,
      optSentFlag: false,
      errorMsg: '验证码不能为空'
    };
  }

  pageChange(params) {
    this.props.history.push(params);
  }

  getPhoneCode() {
    API.get('v3/loan_applications/credit_auth/send_otp').done(() => {
      this.countDown();
    }).fail((xhr) => {
      utils.errorHandle(xhr, '', this.toast.show);
    });
  }

  confirmOtp() {
    const isOtpValidate = Validate.validate('otp', this.state.verifyCode).result;
    if (!this.state.verifyCode) {
      this.toast.show('验证码不能为空');
      this.setState({verCodeError: 'inline-block'})
    } else if (!this.state.optSentFlag) {
      this.toast.show('请先获取验证码');
    } else if (!isOtpValidate) {
      this.toast.show('请输入正确的验证码');
    } else {
      API.post('v3/loan_applications', {
        tenor: $.fn.cookie('tenor'),
        amount: $.fn.cookie('amount'),
        origin: utils.getChannel() || '',
        welab_product_code: Config.app.productCode,
        otp_code: this.state.verifyCode,
        device_info: {
          ip: '',
          mac: '',
          gps: '',
          uuid: '',
          model: 'web version',
          source_id: 2,
          os_version: '',
          contact_count: 0,
          wdid: $.fn.cookie('browserId')
        }
      }).done(data => {
        this.setState({
          submitState: 'finished'
        })
      }).fail((xhr, error) => {
        utils.errorHandle(xhr, '', this.toast.show);
      })
    }
  }

  handleVerifyCode(e) {
    if (e.target.value.length == 0) {
      this.setState({verCodeError: 'inline-block', verifyCode: e.target.value});
    }
    else {
      this.setState({verCodeError: 'none', verifyCode: e.target.value});
    }
  }

  countDown() {
    this.setState({optSentFlag: true, getVerAllow: false});
    let count = 59;
    this.refs['otpBtn'].disabled = true;
    this.refs['otpBtn'].innerHTML = '60';
    this.intervalId = setInterval(() => {
      if (count <= 0) {
        clearInterval(this.intervalId);
        this.refs['otpBtn'].disabled = false;
        this.refs['otpBtn'].innerHTML = '重新获取';
        this.setState({getVerAllow: true});
      } else {
        this.refs['otpBtn'].innerHTML = `${count}s`;
        count--;
      }
    }, 1000);
  }

  componentDidMount() {
    API.get('jddProfile', {platformPath: 'apply-gateway'}).done((res) => {
      this.setState({
        userName: res.data.name
      })
    }).fail((xhr) => {
      utils.errorHandle(xhr, '', this.toast.show);
    });
  }

  render() {
    const phone = $.fn.cookie('X-User-Mobile'), amount = $.fn.cookie('amount'),
      tenor = $.fn.cookie('tenor').split('M')[0];
    return (
      <FullScreen color='#fff'>
        <Toast ref={t => this.toast = t}></Toast>
        <div className={this.state.submitState != 'finished' ? 'active jdd-submitApply' : 'jdd-submitApply'}>
          <div className="apply-money-wrap"><span className='apply-money'>{amount}</span>元</div>
          <div className="time-limit-wrap">期限: <span className="time-limit">{tenor}个月</span></div>
          <div className="borrower-wrap"><span className="borrower-phone">{this.state.userName}</span> <span
            className="borrower-name">{phone}</span>
          </div>
          <FormGroup withLabel={true} label="验证码">
            <Input ref="mobile" onChange={this.handleVerifyCode.bind(this)} onBlur={this.handleVerifyCode.bind(this)}
                   attributes={{placeholder: "请输入验证码", maxLength: 6}}/>
            <div className="otp-box">
              <button className={this.state.getVerAllow ? 'active' : ''} ref="otpBtn"
                      onClick={this.getPhoneCode.bind(this)}>获取验证码
              </button>
            </div>
          </FormGroup>
          <Agreement ref="agreement" scrollWidth="auto" url="/staff/registAgreement.html" title="同意 "
                     proxy="《借款服务与授权协议》" checked="true"/>
          <div className="btn-box">
            <button className="btn" onClick={this.confirmOtp.bind(this)}>提交</button>
          </div>
        </div>
        <div
          className={this.state.submitState == 'finished' ? 'active jdd-submitApply-finished' : 'jdd-submitApply-finished'}>
          <div className="icon-submitStatus"></div>
          <span className='submit-status'>已提交审核</span>
          <div className='status-intro'>正在加速审批中,想第一时间了解审批结果 请关注我来贷公众号"<a className='officeWechat-link'>wolaidaichina</a>"
          </div>
          <div className="btn-box">
            <button className="btn" onClick={this.pageChange.bind(this, 'apply')}>知道了</button>
          </div>
        </div>
        <div className="jdd-submitApply-refused">
          <div className="icon-submitStatus"></div>
          <div className="submitStatus">
            <p>您上次申请被拒绝建议</p>
            <span className='color-FF5D3D'>增加信用认证</span>或<span className="color-FF5D3D">更新资料</span>后再提交
          </div>
          <div className="btn-box">
            <button className="btn" onClick={this.pageChange.bind(this, 'mydata/auth')}>补充资料</button>
            <button className="btn notFill" onClick={this.pageChange.bind(this, 'apply')}>继续提交</button>
          </div>
        </div>
      </FullScreen>
    )
  }
}

export default SubmitApply;